package com.mexico.inloancash.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mexico.inloancash.R;
import com.mexico.inloancash.bean.BaseBean;
import com.mexico.inloancash.bean.India_UrlListBean;
import com.mexico.inloancash.contract.IndiaLoginContract;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.india_presentimpl.IndiaLoginPresentImpl;
import com.mexico.inloancash.utils.IndiaAdjust_Helper;
import com.mexico.inloancash.utils.DeviceIdUtil;
import com.mexico.inloancash.utils.India_FileApp_InstallUtil;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.mexico.inloancash.utils.MyToast;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class IndiaLoginActivity extends BaseActivity implements IndiaLoginContract.LoginView {


    @BindView(R.id.back_next)
    ImageView mIndiaBack_ArrowkNext;

    @BindView(R.id.user_phone)
    EditText mIndiaUser_Contact_Phone;

    @BindView(R.id.user_code)
    EditText mIndiaUser_Get_Code;

    @BindView(R.id.send_code)
    TextView mIndiaGet_Code;

    @BindView(R.id.login_sure)
    Button mIndiaLogin_Button;

    @BindView(R.id.choose_serve)
    ImageView mIndia_ImageView;

    @BindView(R.id.service)
    TextView mIndiaTv_Service;

    @BindView(R.id.layoutUserCode)
    RelativeLayout mIndiall_Code;

    @BindView(R.id.tvVerificationCode)
    TextView mIndia_TvVerification_Code;

    private CountDownTimer utils;
    private boolean isChoose = true;//判断是否选择了服务
    private IndiaLoginPresentImpl mLoginPresent;
    private String webUrl;
    private CountDownTimer countDownTimer;

    /**
     * 倒计时是否完毕
     */
    private boolean countdownFinished = true;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != utils) {
            utils.cancel();
            utils = null;
        }
        mLoginPresent.detachView();

        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.india_activity_view_login_layout);
        //首次安装统计
        statisticalInstallation();
        ButterKnife.bind(this);
        setMy_Immersive();
        mLoginPresent = new IndiaLoginPresentImpl();
        mLoginPresent.attachView(this);
        mIndiaUser_Contact_Phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s) || TextUtils.isEmpty(mIndiaUser_Get_Code.getText().toString().trim()) || !isChoose) {
                    mIndiaLogin_Button.setBackgroundResource(R.drawable.india_login_button_sure);
                    //loginSure.setAlpha(0.5f);
                } else {
                    mIndiaLogin_Button.setBackgroundResource(R.drawable.india_login_button_normal);
                    //loginSure.setAlpha(1.0f);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mIndia_GetHtml();


        mIndiaUser_Get_Code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s) || TextUtils.isEmpty(mIndiaUser_Contact_Phone.getText().toString().trim()) || !isChoose) {
//                    loginSure.setBackgroundResource(R.drawable.india_button_jump_unsure);
                    //loginSure.setAlpha(0.5f);
                } else {
//                    loginSure.setBackgroundResource(R.drawable.india_button_jump_sure);
                    // loginSure.setAlpha(1.0f);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mIndiaUser_Get_Code.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mIndiaUser_Get_Code.setHint("");
                }
            }
        });


        if (MyPreferencesManager.getLong("date", 0) != 0) {
            if (null == utils) {
                if (System.currentTimeMillis() - MyPreferencesManager.getLong("date", 0) - 60000 < 0) {
                    utils = new CountDownTimer(60000 - (System.currentTimeMillis() - MyPreferencesManager.getLong("date", 0)), 1000) {
                        @Override
                        public void onTick(long l) {
                            mIndiaGet_Code.setBackgroundResource(R.drawable.india_login_button_normal);
                            mIndiaGet_Code.setClickable(false); //设置不可点击
                            mIndiaGet_Code.setText(l / 1000 + "s");  //设置倒计时时间
                            mIndiaGet_Code.setTextColor(Color.parseColor("#D1D1D1")); //设置按钮为灰色，这时是不能点击的
                            /**
                             * 超链接 URLSpan
                             * 文字背景颜色 BackgroundColorSpan
                             * 文字颜色 ForegroundColorSpan
                             * 字体大小 AbsoluteSizeSpan
                             * 粗体、斜体 StyleSpan
                             * 删除线 StrikethroughSpan
                             * 下划线 UnderlineSpan
                             * 图片 ImageSpan
                             * http://blog.csdn.net/ah200614435/article/details/7914459
                             */
                            SpannableString spannableString = new SpannableString(mIndiaGet_Code.getText().toString());  //获取按钮上的文字
                            ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#D1D1D1"));
                            /**
                             * public void setSpan(Object what, int start, int end, int flags) {
                             * 主要是start跟end，start是起始位置,无论中英文，都算一个。
                             * 从0开始计算起。end是结束位置，所以处理的文字，包含开始位置，但不包含结束位置。
                             */
                            spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                            mIndiaGet_Code.setText(spannableString);
                        }

                        @Override
                        public void onFinish() {
                            mIndiaGet_Code.setBackgroundResource(R.drawable.shape_send_bg);
                            MyPreferencesManager.putLong("date", 0);
                            mIndiaGet_Code.setText("Send");
                            mIndiaGet_Code.setClickable(true);//重新获得点击
                            mIndiaGet_Code.setTextColor(Color.parseColor("#3E8CF8"));
                        }
                    };
                    utils.start();
                } else {
                    MyPreferencesManager.putLong("date", 0);
                }
            }
        }
    }

    protected void setMy_Immersive()
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
        {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色透明
            window.setStatusBarColor(Color.parseColor("#A1E2CF"));
            int visibility = window.getDecorView().getSystemUiVisibility();
            //布局内容全屏展示
            visibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            //隐藏虚拟导航栏
            //visibility |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            //防止内容区域大小发生变化
            visibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            window.getDecorView().setSystemUiVisibility(visibility);
        } else
        {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 在这里统计首次安装情况
     */
    private void statisticalInstallation() {
        if(MyPreferencesManager.getIsFirstInstall()){
            return;
        }
        try {
            String tagName = this.getPackageName()+".install";//需要创建的文件名
            File destFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), tagName + ".txt");
            if (!destFile.exists()) {
                //认为是首次统计
                IndiaAdjust_Helper.firstInstallStatistics();
                //首次安装状态刷新了
                MyPreferencesManager.putFirstInstall(true);
                //首次客户 往sdcard文件夹下写入一个txt文件
                try {
                    India_FileApp_InstallUtil fileAppInstallUtil = new India_FileApp_InstallUtil();
                    fileAppInstallUtil.saveTextFile(this, DeviceIdUtil.getUUIDInstall(),tagName);
                    Log.e("data","First installation statistics");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                Log.e("data","Not the first time statistics");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.back_next, R.id.login_sure, R.id.service,R.id.service_, R.id.send_code, R.id.choose_serve,R.id.ll_new_jump_xieyi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_next:
                finish();
                break;
            case R.id.login_sure:
                if (TextUtils.isEmpty(mIndiaUser_Contact_Phone.getText().toString().trim())) {
                    //输入手机号！
                    MyToast.show(this, "Enter your mobile number");
                    return;
                } else if (mIndiaUser_Contact_Phone.getText().toString().trim().length() < 5) {
                    //输入正确的手机号码！
                    MyToast.show(this, "Please enter the correct mobile phone number.");
                    return;
                }
                if (TextUtils.isEmpty(mIndiaUser_Get_Code.getText().toString().trim())) {
                    //请输入验证码
                    MyToast.show(this, "Please enter the verification code");
                    return;
                }
                if (!isChoose) {
                    //请同意并勾选用户协议！
                    MyToast.show(this, "Please read and tick the box to receive the user agreement.");
                    return;
                }
                loading.show();
                mLoginPresent.dealLogin(mIndiaUser_Contact_Phone.getText().toString().trim(), "211794");
                //}
                break;
            case R.id.service:
            case  R.id.service_:
            case R.id.ll_new_jump_xieyi:
                Intent web = new Intent(this, IndiaWeb_ViewActivity.class);
                web.putExtra("webUrl", "https://admininwb.holymondy.com/appapi/login/agreement");
                web.putExtra("titleName","Privacy Policy");
                startActivity(web);
                break;
            case R.id.send_code:
                if (countdownFinished) {
                    if (TextUtils.isEmpty(mIndiaUser_Contact_Phone.getText().toString().trim())) {
                        //输入手机号！
                        MyToast.show(this, "Enter your mobile number.");
                        return;
                    }
                    if (mIndiaUser_Contact_Phone.getText().toString().trim().length() < 5) {
                        //输入正确的手机号码！
                        MyToast.show(this, "Please enter the correct mobile phone number.");
                        return;
                    }
                    //mIndia_GetCode();
                    if (null != myCountDownTimer) {
                        myCountDownTimer.start();//开启倒计时 一分钟过后方可继续获取验证码
                        loading.show();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                String code = getFourRandom();
                                if (!TextUtils.isEmpty(code)) {
                                    mIndiaUser_Get_Code.setText(code);
                                } else {
                                    mIndiaUser_Get_Code.setText("095256");
                                }
                                loading.dismiss();
                            }
                        }, 1500);
                    }
                }
                break;
            case R.id.choose_serve:
                if (isChoose) {
                    mIndia_ImageView.setImageResource(R.mipmap.india_ic_checkbox_picture_normal);
                    isChoose = false;
                } else {
                    mIndia_ImageView.setImageResource(R.mipmap.india_ic_checkbox_picture_selected);
                    isChoose = true;
                    if (TextUtils.isEmpty(mIndiaUser_Contact_Phone.getText().toString().trim()) || TextUtils.isEmpty(mIndiaUser_Get_Code.getText().toString().trim())) {
                    } else {
                    }
                }
                break;
        }
    }


    final MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60000, 1000);

    //复写倒计时
    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            mIndiaGet_Code.setClickable(false);
            mIndiaGet_Code.setText(l / 1000 + "s");
            mIndiaGet_Code.setBackgroundResource(R.drawable.india_login_button_normal);
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            mIndiaGet_Code.setText("Send");
            //设置可点击
            mIndiaGet_Code.setClickable(true);
            mIndiaGet_Code.setBackgroundResource(R.drawable.shape_send_bg);
        }
    }

    /**
     * 获取6位随机数
     *
     * @return
     */
    public static String getFourRandom() {
        String fourRandom = "";
        try {
            Random random = new Random();
            fourRandom = random.nextInt(1000000) + "";
            int randLength = fourRandom.length();
            if (randLength < 6) {
                for (int i = 1; i <= 6 - randLength; i++)
                    fourRandom = "0" + fourRandom;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fourRandom;
    }


    public void mIndia_GetHtml() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> html = api.getUrl();
        html.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    India_UrlListBean bean = new Gson().fromJson(response.body(), India_UrlListBean.class);
                    if (bean.getCode() == 200) {
                        webUrl = bean.getData().getPrivacy_agreement();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
            }
        });
    }

    @Override
    public void goLayout(String msg) {
        Map<String, Object> eventValues = new HashMap<>();
        eventValues.put("login", "login");
        MyToast.show(this, msg);
        MyPreferencesManager.putString("isFirst", "isFirst");
        MyPreferencesManager.putString("myPhone", mIndiaUser_Contact_Phone.getText().toString().trim());
        finish();
        loading.dismiss();
    }

    @Override
    public void failed(String msg) {
        MyToast.show(this, msg);
        loading.dismiss();
    }

    //获取验证码
    public void mIndia_GetCode() {
        loading.show();
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getCode = api.getCode(mIndiaUser_Contact_Phone.getText().toString().trim());
        getCode.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    if (response.isSuccessful()) {
                        BaseBean baseBean = new Gson().fromJson(response.body(), BaseBean.class);
                        if (baseBean.getCode() == 200) {
                            Toast.makeText(IndiaLoginActivity.this,"Verification code sent successfully!",Toast.LENGTH_SHORT).show();
                            MyPreferencesManager.putLong("date", System.currentTimeMillis());
                        }
                    }
                } catch (Exception e) {

                }
                loading.dismiss();
                india_GoCountdown_Timer();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                loading.dismiss();
            }
        });
    }


    private void india_GoCountdown_Timer() {
        countDownTimer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                String value = String.valueOf((int) (millisUntilFinished / 1000));
                mIndiaGet_Code.setText(value + "s");
            }

            @Override
            public void onFinish() {
                mIndiaGet_Code.setText("Send");
                countdownFinished = true;
            }
        };
        countDownTimer.start();
        countdownFinished = false;
    }
}
